<template>
  <div :id="playerId" class="video-player"></div>
</template>

<script>
import Player from 'xgplayer';
import 'xgplayer/dist/index.min.css';

export default {
  props: {
    url: {
      type: String,
      default: '',
    },
    index: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      player: null,
      playerId: `video-player-${this._uid}`,
    };
  },
  mounted() {
    console.log('传过来的url:', this.url);
    this.initPlayer();
  },
  watch: {
    url: {
      handler(newValue, oldValue) {
        if (!this.player) {
          this.initPlayer();
          return;
        }
        this.player.src = newValue;
      },
    },
  },
  methods: {
    initPlayer() {
      if (!this.url) return console.warn('url is not exist');
      const config = {
        id: this.playerId,
        url: this.url,
        fluid: true,
        playbackRate: [0.5, 0.75, 1, 1.5, 2],
        defaultPlaybackRate: 1,
        playsinline: this.isAppleDevice(),
        'x5-video-player-type': 'h5',
        'x5-video-orientation': 'portraint',
        pip: true,
        pipConfig: {
          bottom: 100,
          right: 100,
          width: 320,
          height: 180,
        },
        videoInit: true,
        autoplay: true,
      };

      this.player = new Player(config);

      if (this.player) {
        this.player.on('play', () => {
          this.$emit('play', this.index);
        });
        this.player.on('pause', () => {
          this.$emit('pause', this.index);
        });
      }
    },
    isAppleDevice() {
      const ua = navigator.userAgent.toLowerCase();
      return /iphone|ipad|phone|Mac/i.test(ua);
    },
  },
  beforeDestroy() {
    if (this.player) {
      this.player.destroy();
    }
  },
};
</script>

<style scoped>
.video-player {
  width: 100%;
  height: 100%;
}
</style>
